package jude.java.money.batch.task;

import static jude.java.money.batch.Keys.GSPAY_SITE_ID;
import static jude.java.money.batch.Keys.RPPAY_KEY;
import static jude.java.money.batch.Keys.RPPAY_SITE_ID;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import jude.java.money.batch.Definition;
import jude.java.money.batch.Parameter;
import jude.java.money.batch.memory.Sites;
import jude.java.money.batch.task.expand.Pretreatment;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.lang.StringUtils;

/**
 * 批量执行SQL
 * 仅支持ZenCart
 * */
public class BatchSQL extends BatchTask<String[]> {
	
	public static final String CODE = 
	"$sql=get_magic_quotes_gpc()==1?stripslashes($_POST['sql']):$_POST['sql'];" +
	"$sql=str_replace('"+Definition.DB_PREFIX+"',DB_PREFIX,trim($sql));\r\n" +
//	"echo $sql;\r\n"+
	"error_reporting(E_ALL);\r\n"+
//	"include_once(GetRootPath().'/includes/configure.php');\r\n"+
//	"\r\n"+
//	"function GetRootPath(){\r\n"+
//	"	$RealPath = realpath('./');\r\n"+
//	"	$SelfPath = $_SERVER['PHP_SELF'];\r\n"+
//	"	$SelfPath = substr($SelfPath, 0, strrpos($SelfPath,'/'));\r\n"+
//	"	return substr($RealPath, 0, strlen($RealPath) - strlen($SelfPath));\r\n"+
//	"}\r\n"+
	"function super_query($sql){\r\n"+
	"   if (!function_exists('mysql_connect')) die('MySQL Connector not installed');\r\n"+
	"	$con = mysql_connect(DB_SERVER,DB_SERVER_USERNAME,base64_decode(DB_SERVER_PASSWORD)) or mysql_connect(DB_SERVER,DB_SERVER_USERNAME,DB_SERVER_PASSWORD) or die('cant connect server:'.DB_SERVER); \r\n"+
	"	mysql_select_db(DB_DATABASE,$con) or die('cant connect db:'.DB_DATABASE); \r\n"+
	"	$rst = mysql_query($sql,$con) or die('sql error:'.$sql); \r\n"+
	"	\r\n" +
	"	$query=(strtolower(substr($sql,0,6))=='select');" +
	"	if (!$query)echo mysql_affected_rows();\r\n" +
	"	else{\r\n" +
	"		$count = mysql_num_rows($rst);\r\n" +
	"		if($count==0)die('-EMPTY-');\r\n" +
	"		$num_fields = mysql_num_fields($rst);\r\n"+
 	"		if($count==1&&$num_fields==1){$row=mysql_fetch_row($rst);die($row[0]);}\r\n" +
 	"		if ($num_fields){\r\n"+
	"			echo '<table border=\"1\" cellpadding=\"0\" cellspacing=\"0\">';\r\n"+
	"			if($num_fields>1){\r\n" +
	"				echo '<tr>';\r\n"+
	"				for($i=0;$i<$num_fields;$i++)\r\n"+
	"					echo '<th> '.mysql_field_name($rst,$i).'</th>'; \r\n"+
	"				echo '</tr>';\r\n"+
	"			}\r\n" +
	"			while($row=mysql_fetch_row($rst)){\r\n"+
	"				echo '<tr>';\r\n"+
	"				for($i=0;$i<$num_fields;$i++) echo '<td> '.$row[$i].'</td>'; \r\n"+
	"				echo '</tr>';\r\n"+
	"			}\r\n"+
	"			echo '</table>';\r\n"+
	"			mysql_free_result($rst);\r\n"+
	"		}else{\r\n"+
	"			echo $rst.' rows effected.';\r\n"+
	"		}\r\n"+
	"	}\r\n" +
	"	mysql_close($con);\r\n"+
	"}\r\n"+
	"super_query($sql);\r\n"+
	"\r\n"+
	"die();";
	
	public BatchSQL(Parameter<String[]> p) {
		super(p);
		assertType(Definition.TYPE_ZENCART);
	}
	
	@Override
	protected String getLabel() {
		return "SQL";
	}
	
	protected void execute(String site, String url, int group, int index) throws IOException {
		HttpClient client = getHttpClient();
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		NameValuePair key = new NameValuePair("key", P.KEY);
		String[] sqls = P.PARAMS;
		for (int i = 0; i < sqls.length; i++) {
//			print("\r\n").print(i+1).print("\t");
			params.clear();
			params.add(key);
			String sql = sqls[i];
			if (pretreatment != null) {
				sql = pretreatment.process(site, group, index, sql);
			}
			params.add(new NameValuePair("value", CODE));
			params.add(new NameValuePair("sql", sql));
			PostMethod post = getPostMethod(url, params);
			shieldPost(i, site, client, post);
		}
	}
	
	@Override
	protected void createPatch() {
		String[] params = P.PARAMS;
		System.out.println();
		for (int i = 0; i < params.length; i++) {
			String sql = params[i];
			System.out.println(sql + ";");
		}
		System.out.println();
	}
	
	public static class ZencartSQLCallback implements Pretreatment {
		@Override
		public String process(String site, int group, int index, String sql) {
			if (sql.contains(RPPAY_SITE_ID)) {
				String siteId = Sites.getRppayId(site);
				sql = StringUtils.replace(sql, RPPAY_SITE_ID, siteId);
			}
			if (sql.contains(RPPAY_KEY)) {
				sql = StringUtils.replace(sql, RPPAY_KEY, Sites.RP_KEY);
			}
			if (sql.contains(GSPAY_SITE_ID)) {
				String siteId = Sites.getGspayId(site);
				sql = StringUtils.replace(sql, GSPAY_SITE_ID, siteId);
			}
			return sql;
		}
	}
}
